1 /*
2 * Copyright (C) 2008 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.common.primitives;
18
19 import static com.google.common.base.Preconditions.checkArgument;
20 import static com.google.common.base.Preconditions.checkElementIndex;
21 import static com.google.common.base.Preconditions.checkNotNull;
22 import static com.google.common.base.Preconditions.checkPositionIndexes;
23
24 import com.google.common.annotations.Beta;
25 import com.google.common.annotations.GwtCompatible;
26 import com.google.common.base.Converter;
27
28 import java.io.Serializable;
29 import java.util.AbstractList;
30 import java.util.Arrays;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.Comparator;
34 import java.util.List;
35 import java.util.RandomAccess;
36
37 import javax.annotation.CheckForNull;
38
39 /**
40 * Static utility methods pertaining to {@code int} primitives, that are not
41 * already found in either {@link Integer} or {@link Arrays}.
42 *
43 * <p>See the Guava User Guide article on <a href=
44 * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
45 * primitive utilities</a>.
46 *
47 * @author Kevin Bourrillion
48 * @since 1.0
49 */
50 @GwtCompatible(emulated = true)
51 public final class Ints {
52 private Ints() {}
53
54 /**
55 * The number of bytes required to represent a primitive {@code int}
56 * value.
57 */
58 public static final int BYTES = Integer.SIZE / Byte.SIZE;
59
60 /**
61 * The largest power of two that can be represented as an {@code int}.
62 *
63 * @since 10.0
64 */
65 public static final int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2);
66
67 /**
68 * Returns a hash code for {@code value}; equal to the result of invoking
69 * {@code ((Integer) value).hashCode()}.
70 *
71 * @param value a primitive {@code int} value
72 * @return a hash code for the value
73 */
74 public static int hashCode(int value) {
75 return value;
76 }
77
78 /**
79 * Returns the {@code int} value that is equal to {@code value}, if possible.
80 *
81 * @param value any value in the range of the {@code int} type
82 * @return the {@code int} value that equals {@code value}
83 * @throws IllegalArgumentException if {@code value} is greater than {@link
84 * Integer#MAX_VALUE} or less than {@link Integer#MIN_VALUE}
85 */
86 public static int checkedCast(long value) {
87 int result = (int) value;
88 if (result != value) {
89 // don't use checkArgument here, to avoid boxing
90 throw new IllegalArgumentException("Out of range: " + value);
91 }
92 return result;
93 }
94
95 /**
96 * Returns the {@code int} nearest in value to {@code value}.
97 *
98 * @param value any {@code long} value
99 * @return the same value cast to {@code int} if it is in the range of the
100 * {@code int} type, {@link Integer#MAX_VALUE} if it is too large,
101 * or {@link Integer#MIN_VALUE} if it is too small
102 */
103 public static int saturatedCast(long value) {
104 if (value > Integer.MAX_VALUE) {
105 return Integer.MAX_VALUE;
106 }
107 if (value < Integer.MIN_VALUE) {
108 return Integer.MIN_VALUE;
109 }
110 return (int) value;
111 }
112
113 /**
114 * Compares the two specified {@code int} values. The sign of the value
115 * returned is the same as that of {@code ((Integer) a).compareTo(b)}.
116 *
117 * <p><b>Note for Java 7 and later:</b> this method should be treated as
118 * deprecated; use the equivalent {@link Integer#compare} method instead.
119 *
120 * @param a the first {@code int} to compare
121 * @param b the second {@code int} to compare
122 * @return a negative value if {@code a} is less than {@code b}; a positive
123 * value if {@code a} is greater than {@code b}; or zero if they are equal
124 */
125 public static int compare(int a, int b) {
126 return (a < b) ? -1 : ((a > b) ? 1 : 0);
127 }
128
129 /**
130 * Returns {@code true} if {@code target} is present as an element anywhere in
131 * {@code array}.
132 *
133 * @param array an array of {@code int} values, possibly empty
134 * @param target a primitive {@code int} value
135 * @return {@code true} if {@code array[i] == target} for some value of {@code
136 * i}
137 */
138 public static boolean contains(int[] array, int target) {
139 for (int value : array) {
140 if (value == target) {
141 return true;
142 }
143 }
144 return false;
145 }
146
147 /**
148 * Returns the index of the first appearance of the value {@code target} in
149 * {@code array}.
150 *
151 * @param array an array of {@code int} values, possibly empty
152 * @param target a primitive {@code int} value
153 * @return the least index {@code i} for which {@code array[i] == target}, or
154 * {@code -1} if no such index exists.
155 */
156 public static int indexOf(int[] array, int target) {
157 return indexOf(array, target, 0, array.length);
158 }
159
160 // TODO(kevinb): consider making this public
161 private static int indexOf(
162 int[] array, int target, int start, int end) {
163 for (int i = start; i < end; i++) {
164 if (array[i] == target) {
165 return i;
166 }
167 }
168 return -1;
169 }
170
171 /**
172 * Returns the start position of the first occurrence of the specified {@code
173 * target} within {@code array}, or {@code -1} if there is no such occurrence.
174 *
175 * <p>More formally, returns the lowest index {@code i} such that {@code
176 * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
177 * the same elements as {@code target}.
178 *
179 * @param array the array to search for the sequence {@code target}
180 * @param target the array to search for as a sub-sequence of {@code array}
181 */
182 public static int indexOf(int[] array, int[] target) {
183 checkNotNull(array, "array");
184 checkNotNull(target, "target");
185 if (target.length == 0) {
186 return 0;
187 }
188
189 outer:
190 for (int i = 0; i < array.length - target.length + 1; i++) {
191 for (int j = 0; j < target.length; j++) {
192 if (array[i + j] != target[j]) {
193 continue outer;
194 }
195 }
196 return i;
197 }
198 return -1;
199 }
200
201 /**
202 * Returns the index of the last appearance of the value {@code target} in
203 * {@code array}.
204 *
205 * @param array an array of {@code int} values, possibly empty
206 * @param target a primitive {@code int} value
207 * @return the greatest index {@code i} for which {@code array[i] == target},
208 * or {@code -1} if no such index exists.
209 */
210 public static int lastIndexOf(int[] array, int target) {
211 return lastIndexOf(array, target, 0, array.length);
212 }
213
214 // TODO(kevinb): consider making this public
215 private static int lastIndexOf(
216 int[] array, int target, int start, int end) {
217 for (int i = end - 1; i >= start; i--) {
218 if (array[i] == target) {
219 return i;
220 }
221 }
222 return -1;
223 }
224
225 /**
226 * Returns the least value present in {@code array}.
227 *
228 * @param array a <i>nonempty</i> array of {@code int} values
229 * @return the value present in {@code array} that is less than or equal to
230 * every other value in the array
231 * @throws IllegalArgumentException if {@code array} is empty
232 */
233 public static int min(int... array) {
234 checkArgument(array.length > 0);
235 int min = array[0];
236 for (int i = 1; i < array.length; i++) {
237 if (array[i] < min) {
238 min = array[i];
239 }
240 }
241 return min;
242 }
243
244 /**
245 * Returns the greatest value present in {@code array}.
246 *
247 * @param array a <i>nonempty</i> array of {@code int} values
248 * @return the value present in {@code array} that is greater than or equal to
249 * every other value in the array
250 * @throws IllegalArgumentException if {@code array} is empty
251 */
252 public static int max(int... array) {
253 checkArgument(array.length > 0);
254 int max = array[0];
255 for (int i = 1; i < array.length; i++) {
256 if (array[i] > max) {
257 max = array[i];
258 }
259 }
260 return max;
261 }
262
263 /**
264 * Returns the values from each provided array combined into a single array.
265 * For example, {@code concat(new int[] {a, b}, new int[] {}, new
266 * int[] {c}} returns the array {@code {a, b, c}}.
267 *
268 * @param arrays zero or more {@code int} arrays
269 * @return a single array containing all the values from the source arrays, in
270 * order
271 */
272 public static int[] concat(int[]... arrays) {
273 int length = 0;
274 for (int[] array : arrays) {
275 length += array.length;
276 }
277 int[] result = new int[length];
278 int pos = 0;
279 for (int[] array : arrays) {
280 System.arraycopy(array, 0, result, pos, array.length);
281 pos += array.length;
282 }
283 return result;
284 }
285
286 private static final class IntConverter
287 extends Converter<String, Integer> implements Serializable {
288 static final IntConverter INSTANCE = new IntConverter();
289
290 @Override
291 protected Integer doForward(String value) {
292 return Integer.decode(value);
293 }
294
295 @Override
296 protected String doBackward(Integer value) {
297 return value.toString();
298 }
299
300 @Override
301 public String toString() {
302 return "Ints.stringConverter()";
303 }
304
305 private Object readResolve() {
306 return INSTANCE;
307 }
308 private static final long serialVersionUID = 1;
309 }
310
311 /**
312 * Returns a serializable converter object that converts between strings and
313 * integers using {@link Integer#decode} and {@link Integer#toString()}.
314 *
315 * @since 16.0
316 */
317 @Beta
318 public static Converter<String, Integer> stringConverter() {
319 return IntConverter.INSTANCE;
320 }
321
322 /**
323 * Returns an array containing the same values as {@code array}, but
324 * guaranteed to be of a specified minimum length. If {@code array} already
325 * has a length of at least {@code minLength}, it is returned directly.
326 * Otherwise, a new array of size {@code minLength + padding} is returned,
327 * containing the values of {@code array}, and zeroes in the remaining places.
328 *
329 * @param array the source array
330 * @param minLength the minimum length the returned array must guarantee
331 * @param padding an extra amount to "grow" the array by if growth is
332 * necessary
333 * @throws IllegalArgumentException if {@code minLength} or {@code padding} is
334 * negative
335 * @return an array containing the values of {@code array}, with guaranteed
336 * minimum length {@code minLength}
337 */
338 public static int[] ensureCapacity(
339 int[] array, int minLength, int padding) {
340 checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
341 checkArgument(padding >= 0, "Invalid padding: %s", padding);
342 return (array.length < minLength)
343 ? copyOf(array, minLength + padding)
344 : array;
345 }
346
347 // Arrays.copyOf() requires Java 6
348 private static int[] copyOf(int[] original, int length) {
349 int[] copy = new int[length];
350 System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
351 return copy;
352 }
353
354 /**
355 * Returns a string containing the supplied {@code int} values separated
356 * by {@code separator}. For example, {@code join("-", 1, 2, 3)} returns
357 * the string {@code "1-2-3"}.
358 *
359 * @param separator the text that should appear between consecutive values in
360 * the resulting string (but not at the start or end)
361 * @param array an array of {@code int} values, possibly empty
362 */
363 public static String join(String separator, int... array) {
364 checkNotNull(separator);
365 if (array.length == 0) {
366 return "";
367 }
368
369 // For pre-sizing a builder, just get the right order of magnitude
370 StringBuilder builder = new StringBuilder(array.length * 5);
371 builder.append(array[0]);
372 for (int i = 1; i < array.length; i++) {
373 builder.append(separator).append(array[i]);
374 }
375 return builder.toString();
376 }
377
378 /**
379 * Returns a comparator that compares two {@code int} arrays
380 * lexicographically. That is, it compares, using {@link
381 * #compare(int, int)}), the first pair of values that follow any
382 * common prefix, or when one array is a prefix of the other, treats the
383 * shorter array as the lesser. For example, {@code [] < [1] < [1, 2] < [2]}.
384 *
385 * <p>The returned comparator is inconsistent with {@link
386 * Object#equals(Object)} (since arrays support only identity equality), but
387 * it is consistent with {@link Arrays#equals(int[], int[])}.
388 *
389 * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
390 * Lexicographical order article at Wikipedia</a>
391 * @since 2.0
392 */
393 public static Comparator<int[]> lexicographicalComparator() {
394 return LexicographicalComparator.INSTANCE;
395 }
396
397 private enum LexicographicalComparator implements Comparator<int[]> {
398 INSTANCE;
399
400 @Override
401 public int compare(int[] left, int[] right) {
402 int minLength = Math.min(left.length, right.length);
403 for (int i = 0; i < minLength; i++) {
404 int result = Ints.compare(left[i], right[i]);
405 if (result != 0) {
406 return result;
407 }
408 }
409 return left.length - right.length;
410 }
411 }
412
413 /**
414 * Returns an array containing each value of {@code collection}, converted to
415 * a {@code int} value in the manner of {@link Number#intValue}.
416 *
417 * <p>Elements are copied from the argument collection as if by {@code
418 * collection.toArray()}. Calling this method is as thread-safe as calling
419 * that method.
420 *
421 * @param collection a collection of {@code Number} instances
422 * @return an array containing the same values as {@code collection}, in the
423 * same order, converted to primitives
424 * @throws NullPointerException if {@code collection} or any of its elements
425 * is null
426 * @since 1.0 (parameter was {@code Collection<Integer>} before 12.0)
427 */
428 public static int[] toArray(Collection<? extends Number> collection) {
429 if (collection instanceof IntArrayAsList) {
430 return ((IntArrayAsList) collection).toIntArray();
431 }
432
433 Object[] boxedArray = collection.toArray();
434 int len = boxedArray.length;
435 int[] array = new int[len];
436 for (int i = 0; i < len; i++) {
437 // checkNotNull for GWT (do not optimize)
438 array[i] = ((Number) checkNotNull(boxedArray[i])).intValue();
439 }
440 return array;
441 }
442
443 /**
444 * Returns a fixed-size list backed by the specified array, similar to {@link
445 * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
446 * but any attempt to set a value to {@code null} will result in a {@link
447 * NullPointerException}.
448 *
449 * <p>The returned list maintains the values, but not the identities, of
450 * {@code Integer} objects written to or read from it. For example, whether
451 * {@code list.get(0) == list.get(0)} is true for the returned list is
452 * unspecified.
453 *
454 * @param backingArray the array to back the list
455 * @return a list view of the array
456 */
457 public static List<Integer> asList(int... backingArray) {
458 if (backingArray.length == 0) {
459 return Collections.emptyList();
460 }
461 return new IntArrayAsList(backingArray);
462 }
463
464 @GwtCompatible
465 private static class IntArrayAsList extends AbstractList<Integer>
466 implements RandomAccess, Serializable {
467 final int[] array;
468 final int start;
469 final int end;
470
471 IntArrayAsList(int[] array) {
472 this(array, 0, array.length);
473 }
474
475 IntArrayAsList(int[] array, int start, int end) {
476 this.array = array;
477 this.start = start;
478 this.end = end;
479 }
480
481 @Override public int size() {
482 return end - start;
483 }
484
485 @Override public boolean isEmpty() {
486 return false;
487 }
488
489 @Override public Integer get(int index) {
490 checkElementIndex(index, size());
491 return array[start + index];
492 }
493
494 @Override public boolean contains(Object target) {
495 // Overridden to prevent a ton of boxing
496 return (target instanceof Integer)
497 && Ints.indexOf(array, (Integer) target, start, end) != -1;
498 }
499
500 @Override public int indexOf(Object target) {
501 // Overridden to prevent a ton of boxing
502 if (target instanceof Integer) {
503 int i = Ints.indexOf(array, (Integer) target, start, end);
504 if (i >= 0) {
505 return i - start;
506 }
507 }
508 return -1;
509 }
510
511 @Override public int lastIndexOf(Object target) {
512 // Overridden to prevent a ton of boxing
513 if (target instanceof Integer) {
514 int i = Ints.lastIndexOf(array, (Integer) target, start, end);
515 if (i >= 0) {
516 return i - start;
517 }
518 }
519 return -1;
520 }
521
522 @Override public Integer set(int index, Integer element) {
523 checkElementIndex(index, size());
524 int oldValue = array[start + index];
525 // checkNotNull for GWT (do not optimize)
526 array[start + index] = checkNotNull(element);
527 return oldValue;
528 }
529
530 @Override public List<Integer> subList(int fromIndex, int toIndex) {
531 int size = size();
532 checkPositionIndexes(fromIndex, toIndex, size);
533 if (fromIndex == toIndex) {
534 return Collections.emptyList();
535 }
536 return new IntArrayAsList(array, start + fromIndex, start + toIndex);
537 }
538
539 @Override public boolean equals(Object object) {
540 if (object == this) {
541 return true;
542 }
543 if (object instanceof IntArrayAsList) {
544 IntArrayAsList that = (IntArrayAsList) object;
545 int size = size();
546 if (that.size() != size) {
547 return false;
548 }
549 for (int i = 0; i < size; i++) {
550 if (array[start + i] != that.array[that.start + i]) {
551 return false;
552 }
553 }
554 return true;
555 }
556 return super.equals(object);
557 }
558
559 @Override public int hashCode() {
560 int result = 1;
561 for (int i = start; i < end; i++) {
562 result = 31 * result + Ints.hashCode(array[i]);
563 }
564 return result;
565 }
566
567 @Override public String toString() {
568 StringBuilder builder = new StringBuilder(size() * 5);
569 builder.append('[').append(array[start]);
570 for (int i = start + 1; i < end; i++) {
571 builder.append(", ").append(array[i]);
572 }
573 return builder.append(']').toString();
574 }
575
576 int[] toIntArray() {
577 // Arrays.copyOfRange() is not available under GWT
578 int size = size();
579 int[] result = new int[size];
580 System.arraycopy(array, start, result, 0, size);
581 return result;
582 }
583
584 private static final long serialVersionUID = 0;
585 }
586
587 private static final byte[] asciiDigits = new byte[128];
588
589 static {
590 Arrays.fill(asciiDigits, (byte) -1);
591 for (int i = 0; i <= 9; i++) {
592 asciiDigits['0' + i] = (byte) i;
593 }
594 for (int i = 0; i <= 26; i++) {
595 asciiDigits['A' + i] = (byte) (10 + i);
596 asciiDigits['a' + i] = (byte) (10 + i);
597 }
598 }
599
600 private static int digit(char c) {
601 return (c < 128) ? asciiDigits[c] : -1;
602 }
603
604 /**
605 * Parses the specified string as a signed decimal integer value. The ASCII
606 * character {@code '-'} (<code>'\u002D'</code>) is recognized as the
607 * minus sign.
608 *
609 * <p>Unlike {@link Integer#parseInt(String)}, this method returns
610 * {@code null} instead of throwing an exception if parsing fails.
611 * Additionally, this method only accepts ASCII digits, and returns
612 * {@code null} if non-ASCII digits are present in the string.
613 *
614 * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even
615 * under JDK 7, despite the change to {@link Integer#parseInt(String)} for
616 * that version.
617 *
618 * @param string the string representation of an integer value
619 * @return the integer value represented by {@code string}, or {@code null} if
620 * {@code string} has a length of zero or cannot be parsed as an integer
621 * value
622 * @since 11.0
623 */
624 @Beta
625 @CheckForNull
626 public static Integer tryParse(String string) {
627 return tryParse(string, 10);
628 }
629
630 /**
631 * Parses the specified string as a signed integer value using the specified
632 * radix. The ASCII character {@code '-'} (<code>'\u002D'</code>) is
633 * recognized as the minus sign.
634 *
635 * <p>Unlike {@link Integer#parseInt(String, int)}, this method returns
636 * {@code null} instead of throwing an exception if parsing fails.
637 * Additionally, this method only accepts ASCII digits, and returns
638 * {@code null} if non-ASCII digits are present in the string.
639 *
640 * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even
641 * under JDK 7, despite the change to {@link Integer#parseInt(String, int)}
642 * for that version.
643 *
644 * @param string the string representation of an integer value
645 * @param radix the radix to use when parsing
646 * @return the integer value represented by {@code string} using
647 * {@code radix}, or {@code null} if {@code string} has a length of zero
648 * or cannot be parsed as an integer value
649 * @throws IllegalArgumentException if {@code radix < Character.MIN_RADIX} or
650 * {@code radix > Character.MAX_RADIX}
651 */
652 @CheckForNull static Integer tryParse(
653 String string, int radix) {
654 if (checkNotNull(string).isEmpty()) {
655 return null;
656 }
657 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
658 throw new IllegalArgumentException(
659 "radix must be between MIN_RADIX and MAX_RADIX but was " + radix);
660 }
661 boolean negative = string.charAt(0) == '-';
662 int index = negative ? 1 : 0;
663 if (index == string.length()) {
664 return null;
665 }
666 int digit = digit(string.charAt(index++));
667 if (digit < 0 || digit >= radix) {
668 return null;
669 }
670 int accum = -digit;
671
672 int cap = Integer.MIN_VALUE / radix;
673
674 while (index < string.length()) {
675 digit = digit(string.charAt(index++));
676 if (digit < 0 || digit >= radix || accum < cap) {
677 return null;
678 }
679 accum *= radix;
680 if (accum < Integer.MIN_VALUE + digit) {
681 return null;
682 }
683 accum -= digit;
684 }
685
686 if (negative) {
687 return accum;
688 } else if (accum == Integer.MIN_VALUE) {
689 return null;
690 } else {
691 return -accum;
692 }
693 }
694 }